﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JESAI.Common.Util
{
    public class RebuildSql
    {
        /// <summary>
        /// 把超过1000的查询个数集合拆分成数量splitNum的多组sql的in集合
        /// </summary>
        /// <param name="conditionList">查询个数集合</param>
        /// <param name="splitNum">拆分的间隔数目,例如：1000</param>
        /// <param name="columnName">SQL中引用的字段名</param>
        /// <param name="leftQuote">左单引号</param>
        /// <param name="rightQuote">右单引号</param>
        /// <returns></returns>
        public static string GetSqlStrByList<T>(List<T> conditionList, int splitNum, string columnName, string leftQuote = "'", string rightQuote = "'")
        {
            //sql查询个数限制，不能超过1000.  
            if (splitNum > 1000) return null;
            if (conditionList == null || conditionList.Count == 0) return null;

            var sql = new StringBuilder();
            sql.Append(columnName).Append(" IN ( ");
            for (int i = 0; i < conditionList.Count; i++)
            {
                sql.Append(leftQuote + conditionList[i] + rightQuote + ",");
                if ((i + 1) % splitNum == 0 && (i + 1) < conditionList.Count)
                {
                    sql.Remove(sql.Length - 1, 1).Append(" ) OR ").Append(columnName).Append(" IN (");
                }
            }
            sql.Remove(sql.Length - 1, 1).Append(" )");

            return sql.ToString();
        }

        /// <summary>
        /// 把超过1000的查询个数集合拆分成数量splitNum的多组sql的in集合
        /// </summary>
        /// <param name="conditionList">查询个数集合</param>
        /// <param name="splitStr">拆分的分割符</param>
        /// <param name="splitNum">拆分的间隔数目,例如：1000</param>
        /// <param name="columnName">SQL中引用的字段名</param>
        /// <returns></returns>
        public static string GetSqlStrByArrays(string conditionList, char[] splitStr, int splitNum, string columnName)
        {
            if (string.IsNullOrWhiteSpace(conditionList)) return null;

            string[] arrStr = conditionList.Split(splitStr);
            return GetSqlStrByList(arrStr.ToList(), splitNum, columnName);
        }

        public static string GetSqlStrByList<T>(List<T> conditionList, string columnName, string relation, string left, string right, string connect)
        {
            var sql = new StringBuilder();
            foreach (var condition in conditionList)
            {
                sql.AppendFormat(" {0} {1} {2}{3}{4} {5}", columnName, relation, left, condition, right, connect);
            }
            return sql.ToString().TrimEnd(connect.ToCharArray());
        }
    }
}
